const ajax = {
    get: function (method, url, data, token) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(xhr.response);
                    } else {
                        reject(xhr.status);
                    }
                }
            }
            if (method.toLowerCase() != 'post') {
                //对象转为get参数
                let s = '';
                for (let item in data) {
                    s += '&' + item + '=' + encodeURIComponent(data[item])
                }
                url += '?' + s.slice(1);
            }
            xhr.open(method, url, true);
            xhr.responseType = 'json';
            if (token) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            }
            xhr.send();
        })
    },
    post: function (method, url, data, token) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        resolve(xhr.response);
                    } else {
                        reject(xhr.status);
                    }
                }
            }
            xhr.open(method, url, true);

            if (method.toLowerCase() == 'post' && data.constructor != FormData) {
                xhr.setRequestHeader('Content-Type', 'Application/json');
            }
            if (token) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + token);
            }
            xhr.responseType = 'json';
            // xhr.open(method, url, true);
            if (method.toLowerCase() == 'post') {
                if (data.constructor != FormData) {
                    xhr.send(JSON.stringify(data))
                } else {
                    xhr.send(data);
                }
            }

        })
    }
}
export { ajax }